<script lang="ts" setup>
import { ref, onActivated } from 'vue';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { dialog } from '@/settings/components/dialog';
import { format, parseISO } from 'date-fns';
import { useI18n } from 'vue-i18n';

const listing = ref<Record<string, any>[]>([]);
const pager = ref({});
const loading = ref(false);
const search = ref();
const { success, warning } = useNotification();
const { t } = useI18n();

const selectedKeys = ref<string[]>([]);

const form = ref({
  name: '',
  time: [],
});

const refresh = async (page = 1) => {
  const { isSuccess, data } = await $fetch('/admin/email/getEmailList', {
    method: 'post',
    data: {
      emailOrName: form.value.name,
      showStartTime: form.value.time?.[0],
      showEndTime: form.value.time?.[1],
      pageNum: page,
      pageSize: 20,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    listing.value = data.records;

    pager.value = {
      current: page,
      total: data.total,
    };
  }
}

const remove = async (id: string) => {
  const { isSuccess } = await $fetch('/admin/email/deleteSubscribe', {
    data: {
      emailId: id,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.del'));
    search.value.refresh();
  }
};

const sendEmail = async (isAll: boolean = false) => {
  if (!isAll && selectedKeys.value.length === 0) {
    warning(t('settings.notification.notice1'));
    return;
  }

  const { button, data } = await dialog(() => import('./template-window.vue'));

  if (button !== 'ok') {
    return;
  }

  const { subject, content } = data;

  const params: Record<string, any> = {
    emailTemplateTitle: subject,
    emailTemplateContent: content,
    sendAll: isAll ? 1 : 0,
  }

  if (isAll) {
    params.emailOrName = form.value.name;
    params.showStartTime = form.value.time?.[0];
    params.showEndTime = form.value.time?.[1];
  }
  else {
    params.emailAddressList = listing.value.filter((item) => selectedKeys.value.includes(item.id)).map(item => ({
      emailAddress: item.emailAddress,
      userName: item.userName,
    }));
  }

  const { button: sendButton } = await dialog(() => import('./send-window.vue'), {
    props: {
      params: params.subscribeListRequest,
      recipients: listing.value.filter((item) => selectedKeys.value.includes(item.id)),
    },
  });

  if (sendButton !== 'ok') {
    return;
  }

  const { isSuccess } = await $fetch('/admin/email/sendEmail', {
    method: 'post',
    data: params,
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.notice2'));
    search.value.refresh();
  }
}

onActivated(() => {
  search.value.refresh('reset');
});

const showUser = async (name: string, email: string) => {
  await dialog(() => import('./view-user-window.vue'), {
    props: {
      name,
      email,
    },
  });
}
</script>

<template>
  <OpenPageSection>
    <OpenSearchTable
      :pager="pager"
      :loading="loading"
      @search="refresh"
      ref="search"
    >
      <template #header>
        <AFormItem :label="$t('settings.view.subscription.user.index.column1')">
          <AInput v-model="form.name" allow-clear />
        </AFormItem>
        <AFormItem :label="$t('settings.view.subscription.user.index.column2')">
          <ARangePicker v-model="form.time" />
        </AFormItem>
      </template>

      <template #header-button>
        <ADropdown position="bl">
          <AButton type="primary">
            {{ $t('settings.view.subscription.user.index.button1') }}
            <span class="ml-[8px]"><IconDown /></span>
          </AButton>
          <template #content>
            <ADoption @click="sendEmail()">{{ $t('settings.view.subscription.user.index.condition1') }}</ADoption>
            <ADoption @click="sendEmail(true)">{{ $t('settings.view.subscription.user.index.condition2') }}</ADoption>
          </template>
        </ADropdown>
      </template>

      <template #header-button-extra>
        <OpenRouterButton to="/operator/subscription/user/send-history">{{ $t('settings.view.subscription.user.index.button2') }}</OpenRouterButton>
      </template>

      <template #table="{ pageChange, bordered, loading: tableLoading, pagination }">
        <ATable
          :bordered="bordered"
          :loading="tableLoading"
          :data="listing"
          row-key="id"
          :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: true,
          }"
          :pagination="pagination"
          v-model:selected-keys="selectedKeys"
          @page-change="pageChange"
        >
          <template #columns>
            <ATableColumn :title="$t('settings.view.subscription.user.index.column3')" data-index="userName" />
            <ATableColumn :title="$t('settings.view.subscription.user.index.column4')" data-index="emailAddress" />
            <ATableColumn :title="$t('settings.view.subscription.user.index.column2')">
              <template #cell="{ record }">
                {{ format(parseISO(record.subscribeTime), 'yyyy-MM-dd HH:mm:ss') }}
              </template>
            </ATableColumn>

            <ATableColumn :title="$t('settings.view.subscription.user.index.column5')" :width="200">
              <template #cell="{ record }">
                <div class="button-actions">
                  <AButton size="small" @click="showUser(record.userName, record.emailAddress)">{{ $t('settings.action.look') }}</AButton>
                  <AButton type="primary" status="danger" size="small" @click="remove(record.id)" v-confirm>{{ $t('settings.action.delete') }}</AButton>
                </div>
              </template>
            </ATableColumn>
          </template>
        </ATable>
      </template>

    </OpenSearchTable>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
